package lzy.controller;

import lzy.entity.User;
import lzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/profile")
    public String userProfile(HttpSession session, Model model, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        model.addAttribute("user", user);
        return "user/profile";
    }

    @PostMapping("/user/update-password")
    public String updatePassword(@RequestParam String oldPassword,
                                 @RequestParam String newPassword,
                                 @RequestParam String confirmNewPassword,
                                 HttpSession session,
                                 RedirectAttributes redirectAttributes) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }

        // 验证旧密码
        if (!userService.authenticate(currentUser.getUsername(), oldPassword)) {
            redirectAttributes.addFlashAttribute("error", "旧密码不正确！");
            return "redirect:/user/profile";
        }

        // 验证两次输入的新密码是否一致
        if (!newPassword.equals(confirmNewPassword)) {
            redirectAttributes.addFlashAttribute("error", "两次输入的新密码不一致！");
            return "redirect:/user/profile";
        }

        // 更新密码
        userService.updatePassword(currentUser.getId(), newPassword);

        redirectAttributes.addFlashAttribute("success", "密码修改成功，请重新登录！");
        // 密码修改后强制用户重新登录，以确保会话安全
        session.invalidate();
        return "redirect:/login";
    }


} 